package com.kmproject.haifu.mvp.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DataHelper;
import com.jess.arms.widget.autolayout.AutoToolbar;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.AppConstant;
import com.kmproject.haifu.di.component.DaggerMyCollectionComponent;
import com.kmproject.haifu.mvp.contract.MyCollectionContract;
import com.kmproject.haifu.mvp.model.entity.beans.StatisticsBean;
import com.kmproject.haifu.mvp.model.entity.beans.UserBean;
import com.kmproject.haifu.mvp.presenter.MyCollectionPresenter;
import com.kmproject.haifu.mvp.ui.adapter.FragmentTitlesAdapter;
import com.kmproject.haifu.mvp.ui.fragment.CustomRentingSeekingListFragment;
import com.kmproject.haifu.mvp.ui.fragment.MoreHousePublishRentFragment;
import com.kmproject.haifu.mvp.ui.fragment.MoreHousePublishSecondHouseFragment;
import com.kmproject.haifu.mvp.ui.fragment.MyCollectHouseRentFragment;
import com.kmproject.haifu.mvp.ui.fragment.MyCollectSecondHandHouseFragment;
import com.kmproject.haifu.mvp.ui.widget.NoScrollViewPager;
import com.kmproject.haifu.mvp.ui.widget.ScaleTransitionPagerTitleView;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.jess.arms.utils.Preconditions.checkNotNull;

//import com.kmproject.haifu.mvp.ui.fragment.MyCollectHouseRentFragment;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 07/11/2019 14:57
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class MyCollectionActivity extends BaseActivity<MyCollectionPresenter> implements MyCollectionContract.View {

    @BindView(R.id.toolbar_back)
    RelativeLayout toolbarBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.back_right_icon)
    ImageView backRightIcon;
    @BindView(R.id.back_right_txt)
    TextView backRightTxt;
    @BindView(R.id.toolbar_right)
    RelativeLayout toolbarRight;
    @BindView(R.id.toolbar)
    AutoToolbar toolbar;
    @BindView(R.id.MyCollect_magic_indicator)
    MagicIndicator MyCollectMagicIndicator;
    @BindView(R.id.MyCollect_viewpager)
    NoScrollViewPager MyCollectViewpager;

    List<Fragment> fragments = new ArrayList<>();
    List<String> titles = null;
    private int selectIndex = 0;
    private CustomRentingSeekingListFragment rentSeekingFragment;
    private StatisticsBean mstatisticsBean;
    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerMyCollectionComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_my_collection; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        Intent intent = getIntent();
        if (intent != null) {
            switch (getIntent().getIntExtra("type", 0)) {
                case 0:
                    //点击我的发布进来
                    backRightTxt.setText("已下架");
                    assert mPresenter != null;
                    mPresenter.myCommonPublishCount("publish");
                    break;
                case 1:
                    //点击我的求租进来
                    backRightTxt.setText("");
                    assert mPresenter != null;
                    mPresenter.myCommonPublishCount("publish");
                    break;
                case 2:
                    //点击我的收藏进来
                    backRightTxt.setText("管理");
                    assert mPresenter != null;
                    mPresenter.myCommonPublishCount("collection");
                    break;
            }
            selectIndex = intent.getIntExtra("selectIndex", 0);
        }

        toolbar.setBackgroundColor(ArmsUtils.getColor(this, R.color.color_EDEDED));
        titles = Arrays.asList(getResources().getStringArray(R.array.collect_title));


        backRightTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (getIntent().getIntExtra("type", 0)) {
                    case 0:
                        //去我下架列表
//                        Intent intent3 = new Intent(MyCollectionActivity.this, MyStoreLookObtainedActivity.class);
                        Intent intent3=new Intent(MyCollectionActivity.this,MyObtainedTabHostActivity.class);
                        intent3.putExtra("HousePayWayBean",(Serializable) (((MoreHousePublishRentFragment)fragments.get(0)).getHoustTypes()));
                        intent3.putExtra("type", "userObtained");
                        intent3.putExtra("StatisticsBean",mstatisticsBean);
                        ArmsUtils.startActivity(intent3);
                        break;
                    case 1:

                        break;
                    case 2:
                        switch (MyCollectViewpager.getCurrentItem()) {
                            case 0:
                                if (backRightTxt.getText().equals("管理")) {
                                    ((MyCollectHouseRentFragment) fragments.get(selectIndex == 2 ? 0 : selectIndex)).contralList(true);
                                    backRightTxt.setText("取消");
                                } else {
                                    ((MyCollectHouseRentFragment) fragments.get(selectIndex == 2 ? 0 : selectIndex)).contralList(false);
                                    backRightTxt.setText("管理");
                                }
                                break;
                            case 1:
                                if (backRightTxt.getText().equals("管理")) {
                                    ((CustomRentingSeekingListFragment) fragments.get(selectIndex == 2 ? 0 : selectIndex)).setData(true);
                                    backRightTxt.setText("取消");
                                } else {
                                    ((CustomRentingSeekingListFragment) fragments.get(selectIndex == 2 ? 0 : selectIndex)).setData(false);
                                    backRightTxt.setText("管理");
                                }
                                break;
                            case 2:
                                if (backRightTxt.getText().equals("管理")) {
                                    ((MyCollectSecondHandHouseFragment) fragments.get(2)).contralList(true);
                                    backRightTxt.setText("取消");
                                } else {
                                    ((MyCollectSecondHandHouseFragment) fragments.get(2)).contralList(false);
                                    backRightTxt.setText("管理");
                                }


                                break;
                        }
                        break;
                }
            }
        });
    }

    @Override
    public String reSetTitle() {
        int type = getIntent().getIntExtra("type", 1);
        if (type == 0) {
            return "我的发布";
        } else if (type == 1) {
            return "我的求租";
        } else {
            return "我的收藏";
        }
    }

    /**
     * 获取控件的高度或者宽度  isHeight=true则为测量该控件的高度，isHeight=false则为测量该控件的宽度
     *
     * @param view
     * @param isHeight
     * @return
     */
    public int getViewHeight(View view, boolean isHeight) {
        int result;
        if (view == null) return 0;
        if (isHeight) {
            int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            view.measure(h, 0);
            result = view.getMeasuredHeight();
        } else {
            int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            view.measure(0, w);
            result = view.getMeasuredWidth();
        }
        return result;
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void myCommonPublishCountSuccess(StatisticsBean statisticsBean) {
        mstatisticsBean=statisticsBean;
        titles.set(0, titles.get(0) + ("(" + statisticsBean.getHouseRentCount() + ")"));
        titles.set(1, titles.get(1) + ("(" + statisticsBean.getHouseRentSeekingCount() + ")"));
        titles.set(2, titles.get(2) + ("(" + statisticsBean.getSecondHandCount() + ")"));
        UserBean ub = DataHelper.getDeviceData(this, AppConstant.USER_INFO);
        assert ub != null;
        if (getIntent().getIntExtra("type", 0) == 0) {
            //点击我的发布进来
            fragments.add(MoreHousePublishRentFragment.newInstance());
            rentSeekingFragment = CustomRentingSeekingListFragment.newInstance(ub.getUserId(), 0);
            fragments.add(rentSeekingFragment);
            fragments.add(MoreHousePublishSecondHouseFragment.newInstance());
        } else if (getIntent().getIntExtra("type", 0) == 1) {
            //点击我的求租进来
            fragments.add(MoreHousePublishRentFragment.newInstance());
            rentSeekingFragment = CustomRentingSeekingListFragment.newInstance(ub.getUserId(), 0);
            fragments.add(rentSeekingFragment);
            fragments.add(MoreHousePublishSecondHouseFragment.newInstance());
        } else if (getIntent().getIntExtra("type", 0) == 2) {
            //点击我的收藏进来
            fragments.add(MyCollectHouseRentFragment.newInstance());
            rentSeekingFragment = CustomRentingSeekingListFragment.newInstance(ub.getUserId(), 1);
            fragments.add(rentSeekingFragment);
            fragments.add(MyCollectSecondHandHouseFragment.newInstance());
        }

        MyCollectViewpager.setAdapter(new FragmentTitlesAdapter(getSupportFragmentManager(), this, titles, fragments));

        MyCollectViewpager.setOffscreenPageLimit(3);
        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdjustMode(false);
        commonNavigator.setMinimumWidth(100);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return titles.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {

                SimplePagerTitleView simplePagerTitleView = new ScaleTransitionPagerTitleView(context);
                simplePagerTitleView.setText(" " + titles.get(index) + " ");
                simplePagerTitleView.setWidth((getWindow().getWindowManager().getDefaultDisplay().getWidth()) / 3);
                simplePagerTitleView.setTextSize(16);
                simplePagerTitleView.setNormalColor(getResources().getColor(R.color.color_191919));
                simplePagerTitleView.setSelectedColor(getResources().getColor(R.color.color_191919));
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                layoutParams.setMargins(15, 0, 5, 0);//4个参数按顺序分别是左上右下
                simplePagerTitleView.setLayoutParams(layoutParams);
                simplePagerTitleView.setOnClickListener(v -> {
                    MyCollectViewpager.setCurrentItem(index);
                });

                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator linePagerIndicator = new LinePagerIndicator(context);
                linePagerIndicator.setMode(LinePagerIndicator.MODE_WRAP_CONTENT);
                linePagerIndicator.setLineHeight(7.0f);
                linePagerIndicator.setLineWidth(100);
                linePagerIndicator.setColors(ArmsUtils.getColor(MyCollectionActivity.this, R.color.color_F9D35A));
                return linePagerIndicator;
            }

            @Override
            public float getTitleWeight(Context context, int index) {
                return 1.0f;
            }

        });
        if (getIntent().hasExtra("defaultSelecIndex"))
        {
            MyCollectViewpager.setCurrentItem(getIntent().getIntExtra("defaultSelecIndex",0));
            commonNavigator.onPageSelected(getIntent().getIntExtra("defaultSelecIndex",0));
        }else {
            MyCollectViewpager.setCurrentItem(0);
            commonNavigator.onPageSelected(0);
        }

        commonNavigator.getAdapter().notifyDataSetChanged();
        MyCollectMagicIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(MyCollectMagicIndicator, MyCollectViewpager);

        MyCollectViewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                selectIndex = i;
                if ((getIntent().getIntExtra("type", 0) == 0 || getIntent().getIntExtra("type", 0) == 1) && i == 1) {
                    backRightTxt.setVisibility(View.INVISIBLE);
                }else {
                    backRightTxt.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

        Objects.requireNonNull(MyCollectViewpager.getAdapter()).notifyDataSetChanged();
    }
}
